package double_pointer;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-12-01
 * Time: 12:43
 */
public class TreeNumSum {
    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> lists = new LinkedList<>();
        int order = 0;
        for(int i = 0; i < nums.length - 2; i++) {
            if(i > 0 && order == nums[i]) {
                continue;
            }
            order = nums[i];
            int left = i + 1;
            int right = nums.length - 1;
            int rOrder = Integer.MAX_VALUE;
            int lOrder = Integer.MAX_VALUE;
            while(left < right) {
                while(left < right && nums[left] == lOrder) {
                    left++;
                }
                while(right > left && nums[right] == rOrder) {
                    right--;
                }
                if(right <= left) {
                    break;
                }
                int sum = nums[left] + nums[right];
                if(sum > -nums[i]) {
                    rOrder = nums[right];
                    right--;
                } else if(sum < -nums[i]) {
                    lOrder = nums[left];
                    left++;
                } else {
                    List<Integer> list = new LinkedList<>();
                    list.add(nums[i]);
                    list.add(nums[left]);
                    list.add(nums[right]);
                    lists.add(list);
                    rOrder = nums[right];
                    right--;
                    lOrder = nums[left];
                    left++;
                }
            }
        }
        return lists;
    }

    public static void main(String[] args) {
        threeSum(new int[]{-2,0,0,2,2});
    }
}
